package com.loopj.android.image;

import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.media.image.PixelMap;

/**
 * author zhaoxudong
 * Version 1.0
 * ModifiedBy
 * date 2021-02-26 14:05
 * description 专注于后台图片加载处理的Task类，实现了Runnable接口
 */
public class SmartImageTask implements Runnable {
    private boolean cancelled = false;
    private OnCompleteHandler onCompleteHandler;
    private SmartImage image;
    private Context context;

    /**
     * author zhaoxudong
     * Version 1.0
     * ModifiedBy
     * date 2021-02-26 14:05
     * description 图片加载完成的回调接口OnCompleteListener
     */
    public static class OnCompleteHandler extends EventHandler {
        public OnCompleteHandler(EventRunner runner) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            PixelMap bitmap = (PixelMap) event.object;
            onComplete(bitmap);
        }

        public void onComplete(PixelMap bitmap) {
        }
    }

    /**
     * 用于SmartImageView类中加载完成后的回调接口
     */
    public abstract static class OnCompleteListener {
        public abstract void onComplete();

        /**
         * Convient method to get Bitmap after image is loaded.
         * Override this method to get handle of bitmap
         * Added overloaded implementation to make it backward compatible with previous versions
         *
         * @param bitmap PixelMap
         */
        public void onComplete(PixelMap bitmap) {
            onComplete();
        }
    }

    /**
     * 构造方法，将SmartImage作为参数
     *
     * @param context Context
     * @param image   SmartImage
     */
    public SmartImageTask(Context context, SmartImage image) {
        this.image = image;
        this.context = context;
    }

    @Override
    public void run() {
        if (image != null) {
            complete(image.getBitmap(context));
            context = null;
        }
    }

    public void setOnCompleteHandler(OnCompleteHandler handler) {
        this.onCompleteHandler = handler;
    }

    public void cancel() {
        cancelled = true;
    }

    public void complete(PixelMap bitmap) {
        if (onCompleteHandler != null && !cancelled) {
            int eventId = 0;
            long param = 0;
            Object object = bitmap;
            InnerEvent innerEvent = InnerEvent.get(eventId, param, object);
            onCompleteHandler.sendEvent(innerEvent);
        }
    }
}